from django.db import models
from django.db.models import F

from social.account.models import User
from social.exceptions import InsufficientBalanceException, BalanceNotEnoughException
from social.utils.models import BaseModel
from social.utils.shortcut import get_object_or_none


class Wallet(BaseModel):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='wallet')
    total_balance = models.IntegerField(default=0)
    balance = models.IntegerField(default=0)
    income = models.IntegerField(default=0)
    total_income = models.IntegerField(default=0)
    consume = models.IntegerField(default=0)
    share_ratio = models.IntegerField(default=50)
    alipay = models.CharField(null=True, max_length=100)

    def consume(self, coin):
        if self.balance < coin:
            raise InsufficientBalanceException()
        self.balance = F('balance') - coin
        self.save(update_fields=['balance'])
        return coin

    def receive_gift(self, gift):
        earning = int((self.share_ratio * gift.coin / 10))
        self.income = F('income') + earning
        self.total_income = F('total_income') + earning
        self.save(update_fields=['total_income', 'income'])
        return earning

    def earning(self, coin):
        earning = int((self.share_ratio * coin / 10))
        self.income = F('income') + earning
        self.total_income = F('total_income') + earning
        self.save(update_fields=['total_income', 'income'])
        return earning

    def withdraw(self, amt):
        if self.income < amt:
            raise BalanceNotEnoughException()
        self.income = F('income') - amt
        self.save(update_fields=['income'])


class WalletRecord(BaseModel):
    COIN = "coin"
    INCOME = "income"
    WITHDRAW = "withdraw"
    user = models.ForeignKey(User, related_name='wallet_records', on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    change = models.IntegerField(default=0)
    type = models.CharField(max_length=100)
    # user_id与call_id组合
    user_call_key = models.CharField(null=True, unique=True, max_length=20)

    @classmethod
    def set_av_call_record(cls, user, title, change, _type, call_id):
        key = f'{user.id}_{call_id}'
        record = get_object_or_none(WalletRecord, user_call_key=key)
        if record:
            record.change = F('change') + change
            record.title = title
            record.save(update_fields=['change', 'title'])
        else:
            WalletRecord.objects.create(user=user, title=title, change=change, type=_type,
                                        user_call_key=key)

    class Meta:
        index_together = [
            ("user", "type")
        ]


class VIPHistory(BaseModel):
    user = models.ForeignKey(User, related_name='vip_history', on_delete=models.CASCADE)
    product = models.ForeignKey('Product', related_name='vip_history', on_delete=models.CASCADE)

    class Meta:
        index_together = [
            ("user", "created_at")
        ]


class Product(BaseModel):
    VIP = 1
    COIN = 2
    price = models.IntegerField(default=0)
    coin = models.IntegerField(default=0)
    origin_price = models.IntegerField(default=0)
    type = models.IntegerField(default=0)
    sort = models.IntegerField(default=0)
    month = models.IntegerField(default=0)
    title = models.CharField(max_length=12, null=True)


class Order(BaseModel):
    WAITING = 1
    SUCCESS = 2
    FAILED = 3
    product = models.ForeignKey(Product, related_name='orders', on_delete=models.CASCADE)
    status = models.IntegerField(default=1)
    amount = models.IntegerField(default=0)
    user = models.ForeignKey(User, related_name='orders', on_delete=models.CASCADE)
    pay_client = models.CharField(default='wechat', max_length=12)
    out_trade_no = models.CharField(max_length=32, null=False)
    callback = models.TextField(null=True)


def set_vip_products():
    ps = Product.objects.filter(type=Product.VIP)
    for x in ps:
        x.delete()
    Product.objects.create(price=2800, origin_price=3000, type=Product.VIP, month=1, sort=3, title='最受欢迎')
    Product.objects.create(price=7100, origin_price=9000, type=Product.VIP, month=3, sort=2, title='超值优惠')
    Product.objects.create(price=19800, origin_price=36000, type=Product.VIP, month=12, sort=1, title='节省最多')


def set_coin_products():
    ps = Product.objects.filter(type=Product.COIN)
    for x in ps:
        x.delete()
    Product.objects.create(price=600, origin_price=600, coin=60, type=Product.COIN)
    Product.objects.create(price=3000, origin_price=3000, coin=300, type=Product.COIN)
    Product.objects.create(price=10800, origin_price=10800, coin=1080, type=Product.COIN)
    Product.objects.create(price=48000, origin_price=48000, coin=4800, type=Product.COIN)
    Product.objects.create(price=98000, origin_price=98000, coin=9800, type=Product.COIN)
    Product.objects.create(price=288000, origin_price=288000, coin=28800, type=Product.COIN)
